package org.lcc.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.lcc.model.dto.Sign_inRequest;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ParseExcelUtil {
    public List<Sign_inRequest> parseExcel(InputStream inputStream) throws Exception {
        List<Sign_inRequest> dataList = new ArrayList<>();
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);

        for (Row row : sheet) {
            // 跳过空行和首行
            if (row.getRowNum() == 0 || isRowEmpty(row)) {
                continue;
            }
            Sign_inRequest data = new Sign_inRequest();

            // 获取单元格的值并根据单元格类型处理
            data.setReal_name(getCellValue(row.getCell(0))); // 姓名
            data.setUsername(getCellValue(row.getCell(2))); // 用户名
            data.setSchool_number(getCellValue(row.getCell(3))); // 学号
            data.setPassword(getCellValue(row.getCell(4))); // 密码
            data.setRole(getCellValue(row.getCell(5))); // 角色

            dataList.add(data);
        }

        workbook.close();
        return dataList;
    }

    private boolean isRowEmpty(Row row) {
        for (Cell cell : row) {
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                return false;
            }
        }
        return true;
    }

    private String getCellValue(Cell cell) {
        if (cell == null || cell.getCellType() == CellType.BLANK) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf((int) cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}